/**
 * 
 */
package com.infodms.dms.actions.claim.authorization;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.claim.application.BalanceStatusRecord;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.bean.TtIfMarketBean;
import com.infodms.dms.bean.auditBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.DBLockUtil;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.Utility;
import com.infodms.dms.common.getCompanyId.GetOemcompanyId;
import com.infodms.dms.dao.claim.authorization.BalanceMainDao;
import com.infodms.dms.dao.feedbackMng.MarketQuesOrderDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TcUserPO;
import com.infodms.dms.po.TtAsDealerTypePO;
import com.infodms.dms.po.TtAsWrAdminDeductPO;
import com.infodms.dms.po.TtAsWrBalanceAuthitemPO;
import com.infodms.dms.po.TtAsWrClaimBalancePO;
import com.infodms.dms.po.TtAsWrDeductBalancePO;
import com.infodms.dms.po.TtAsWrFinePO;
import com.infodms.dms.po.TtAsWrSpefeeAuditingPO;
import com.infodms.dms.po.TtAsWrSpefeePO;
import com.infodms.dms.po.TtIfMarketPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * @Title: DealerSupplierInfo.java
 *
 * @Description:CHANADMS
 *
 * @Copyright: Copyright (c) 2010
 *
 * @Company: www.infoservice.com.cn
 * @Date: 2010-8-30
 *
 * @author lishuai 
 * @mail   lishuai103@yahoo.cn	
 * @version 1.0
 * @remark 
 */
@SuppressWarnings("unchecked")
public class BalanceMain {
	private Logger logger = Logger.getLogger(BalanceMain.class);
	private final String initUrl = "/jsp/claim/authorization/balanceMain.jsp";
	private final String delaerUrl = "/jsp/claim/authorization/dealerQuery.jsp";
	private final String financialInitUrl = "/jsp/claim/authorization/financialMain.jsp";
	private final String infoUrl = "/jsp/claim/authorization/balanceMInfo.jsp";
	private final String auditApplyUrl = "/jsp/claim/authorization/auditApply.jsp";
	private final String finInfoUrl = "/jsp/claim/authorization/balanceFInfo.jsp";
	private final String finViewUrl = "/jsp/claim/authorization/balanceInfoView.jsp";
	private final String delaerInfoUrl = "/jsp/claim/authorization/dealerQueryInfo.jsp";
	private final String invoicePrint = "/jsp/claim/authorization/invoicePrint.jsp";
	private final String printUrl = "/jsp/claim/authorization/balancePrint.jsp";
	private final String oemUrl = "/jsp/claim/authorization/oemBanlanceQuery.jsp";
	private final String CLAIM_INIT_URL = "/jsp/claim/authorization/getClaimInit.jsp" ;//汇总打印初始化页面
	private final String PRINTPROTER_URL = "/jsp/claim/authorization/printPorter.jsp" ;
	private final String CLAIM_PRINT_URL = "/jsp/claim/authorization/claimPrint.jsp" ;//汇总打印页面
	private final String PORTER_PRINT_URL = "/jsp/claim/authorization/queryPrintPorter.jsp" ;
	/*
	 * 结算单管理
	 */
	public void balanceMainInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			//取得该用户拥有的产地权限
			String yieldly = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());
			
			act.setOutData("yieldly", yieldly);
			act.setOutData("auditMan", logonUser.getName());
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单管理");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 结算单审核(财务)
	 */
	public void financialMainInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			
			//取得该用户拥有的产地权限
			String yieldly = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());
			
			act.setOutData("yieldly", yieldly);
			act.setForword(financialInitUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单管理");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 结算单管理 根据页面参数查询
	 */
	public void BalanceMainQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode")); //经销商代码
			String yieldly = CommonUtils.checkNull(request.getParamValue("yieldly"));		//产地代码
			String balanceNo = CommonUtils.checkNull(request.getParamValue("balanceNo"));	//结算单号
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate"));	//创建开始时间
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate"));		//创建结束时间
			String status = CommonUtils.checkNull(request.getParamValue("status")); 		//状态
			String person = CommonUtils.checkNull(request.getParamValue("PERSON")); 	    //复核人
			String yieldlys = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());       //该用户拥有的产地权限
			//当开始时间和结束时间相同时
			if(null!=startDate&&!"".equals(startDate)&&null!=endDate&&!"".equals(endDate)){
				startDate = startDate+" 00:00:00";
				endDate = endDate+" 23:59:59";
			}
			/*拼字符串(同时查询多个经销商，不可模糊)if(!dealerCode.equals("")){////截串加单引号
				String[] supp = dealerCode.split(",");
				dealerCode = "";
				for(int i=0;i<supp.length;i++){
					supp[i] = "'"+supp[i]+"'";
					if(!dealerCode.equals("")){
						dealerCode += "," + supp[i];
					}else{
						dealerCode = supp[i];
					}
				}
			}*/
			auditBean bean = new auditBean();
			bean.setDealerCode(dealerCode);
			bean.setYieldly(yieldly);
			bean.setBalanceNo(balanceNo);
			bean.setStartDate(startDate);
			bean.setEndDate(endDate);
			bean.setStatus(status);
			bean.setPerson(person);
			bean.setOemCompanyId(String.valueOf(GetOemcompanyId.getOemCompanyId(logonUser)));
			bean.setYieldlys(yieldlys);
			
			BalanceMainDao dao = new BalanceMainDao();
			//分页方法 begin
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页	
			PageResult<Map<String, Object>> ps = dao.queryAccAuditList(bean,curPage,30);
			//分页方法 end
			act.setOutData("ps", ps);     //向前台传的list 名称是固定的不可改必须用 ps
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算室审核");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 经销商查看开票通知
	 */
	public void delaerBalanceMainQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String yieldly = CommonUtils.checkNull(request.getParamValue("yieldly"));		//产地代码
			String balanceNo = CommonUtils.checkNull(request.getParamValue("balanceNo"));	//结算单号
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate"));	//创建开始时间
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate"));		//创建结束时间
			//当开始时间和结束时间相同时
			if(null!=startDate&&!"".equals(startDate)&&null!=endDate&&!"".equals(endDate)){
				startDate = startDate+" 00:00:00";
				endDate = endDate+" 23:59:59";
			}
			auditBean bean = new auditBean();
			bean.setYieldly(yieldly);
			bean.setBalanceNo(balanceNo);
			bean.setStartDate(startDate);
			bean.setEndDate(endDate);
			bean.setDealerCode(logonUser.getDealerId());
			bean.setOemCompanyId(String.valueOf(GetOemcompanyId.getOemCompanyId(logonUser)));
			
			BalanceMainDao dao = new BalanceMainDao();
			//分页方法 begin
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页	
			PageResult<Map<String, Object>> ps = dao.queryDealerBalanceList(bean,curPage,Constant.PAGE_SIZE);
			//分页方法 end
			act.setOutData("ps", ps);     //向前台传的list 名称是固定的不可改必须用 ps
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算室审核");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void oemBalanceMainQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String yieldly = CommonUtils.checkNull(request.getParamValue("yieldly"));		//产地代码
			String balanceNo = CommonUtils.checkNull(request.getParamValue("balanceNo"));	//结算单号
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate"));	//创建开始时间
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate"));		//创建结束时间
			String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));		//经销商ID
			String yieldlys = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());       //该用户拥有的产地权限
			//当开始时间和结束时间相同时
			if(null!=startDate&&!"".equals(startDate)&&null!=endDate&&!"".equals(endDate)){
				startDate = startDate+" 00:00:00";
				endDate = endDate+" 23:59:59";
			}
			auditBean bean = new auditBean();
			bean.setYieldly(yieldly);
			bean.setBalanceNo(balanceNo);
			bean.setStartDate(startDate);
			bean.setEndDate(endDate);
			bean.setDealerId(dealerId);
			bean.setOemCompanyId(String.valueOf(GetOemcompanyId.getOemCompanyId(logonUser)));
			bean.setYieldlys(yieldlys);
			
			BalanceMainDao dao = new BalanceMainDao();
			//分页方法 begin
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页	
			PageResult<Map<String, Object>> ps = dao.queryOemBalanceList(bean,curPage,Constant.PAGE_SIZE);
			//分页方法 end
			act.setOutData("ps", ps);     //向前台传的list 名称是固定的不可改必须用 ps
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算室审核");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 结算室审核 根据页面参数查询
	 */
	public void financialMainQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode")); //经销商代码
			String yieldly = CommonUtils.checkNull(request.getParamValue("yieldly"));		//产地代码
			String balanceNo = CommonUtils.checkNull(request.getParamValue("balanceNo"));	//结算单号
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate"));	//创建开始时间
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate"));		//创建结束时间
			String status = CommonUtils.checkNull(request.getParamValue("status"));			//状态
			String yieldlys = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());       //该用户拥有的产地权限
			
			/*********iverson add by 2011-01-20*****************************/
			String reviewBy = CommonUtils.checkNull(request.getParamValue("reviewBy"));
			String reviewBeginDate = CommonUtils.checkNull(request.getParamValue("reviewBeginDate"));
			String reviewEndDate = CommonUtils.checkNull(request.getParamValue("reviewEndDate"));
			if(null!=reviewBeginDate&&!"".equals(reviewBeginDate)&&null!=reviewEndDate&&!"".equals(reviewEndDate)){
				reviewBeginDate = reviewBeginDate+" 00:00:00";
				reviewEndDate = reviewEndDate+" 23:59:59";
			}
			/*********iverson add by 2011-01-20*****************************/
			
			//当开始时间和结束时间相同时
			if(null!=startDate&&!"".equals(startDate)&&null!=endDate&&!"".equals(endDate)){
				startDate = startDate+" 00:00:00";
				endDate = endDate+" 23:59:59";
			}
			/*拼字符串(同时查询多个经销商，不可模糊)if(!dealerCode.equals("")){////截串加单引号
				String[] supp = dealerCode.split(",");
				dealerCode = "";
				for(int i=0;i<supp.length;i++){
					supp[i] = "'"+supp[i]+"'";
					if(!dealerCode.equals("")){
						dealerCode += "," + supp[i];
					}else{
						dealerCode = supp[i];
					}
				}
			}*/
			auditBean bean = new auditBean();
			bean.setDealerCode(dealerCode);
			bean.setYieldly(yieldly);
			bean.setBalanceNo(balanceNo);
			bean.setStartDate(startDate);
			bean.setEndDate(endDate);
			bean.setStatus(status);
			/*********iverson add by 2011-01-20*****************************/
			bean.setReviewBy(reviewBy);
			bean.setReviewBeginDate(reviewBeginDate);
			bean.setReviewEndDate(reviewEndDate);
			/*********iverson add by 2011-01-20*****************************/
			bean.setOemCompanyId(String.valueOf(GetOemcompanyId.getOemCompanyId(logonUser)));
			bean.setYieldlys(yieldlys);
			
			BalanceMainDao dao = new BalanceMainDao();
			//分页方法 begin
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页	
			PageResult<Map<String, Object>> ps = dao.queryFinancialMain(bean,curPage,Constant.PAGE_SIZE);
			//分页方法 end
			act.setOutData("ps", ps);//向前台传的list 名称是固定的不可改必须用 ps
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算室审核");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 查看结算单明细
	 */
	public void queryBalanceInfo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String id = request.getParamValue("id");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getBalanceMainMapView(id);//结算单主表信息
			List<Map<String, Object>> list = dao.getBalanceMainList(id);//结算单子表信息
			//countMarketFee(map, act);//市场工单处理费用 
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setForword(infoUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单明细");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 复核申请打印
	 */
	public void queryPrintInfo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String id = request.getParamValue("id");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getBalancePrintMap(id);//结算单主表信息
			List<Map<String, Object>> list = dao.getBalanceMainList1(id);//结算单子表信息
			List l = dao.getDate(id) ;
			if(l.size()>0){
				act.setOutData("audit", (TtAsWrBalanceAuthitemPO)l.get(0));
			}
			//countMarketFee(map, act);//市场工单处理费用 
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setForword(printUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单明细");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 复核申请
	 * 2010-11-04 修改 特殊外出费用和市场工单费用 已经在结算单生成时统计
	 *            现在不再继续统计
	 */
	public void queryBalanceAudit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String id = request.getParamValue("id");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getBalanceMainMap(id);//结算单主表信息
			List<Map<String, Object>> list = dao.getBalanceMainList(id);//结算单子表信息
			//countMarketFee(map, act);//市场工单处理费用 
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setForword(auditApplyUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"复核申请");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 
	* @Title: countMarketFee 
	* @Description: TODO(计算市场工单处理费用和总费用) 
	* @param @param map 主表信息
	* @param @param act    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	@SuppressWarnings("unused")
	private void countMarketFee(Map<String, Object> map, ActionContext act) {
		BalanceMainDao dao = new BalanceMainDao();
		if (null != map && map.size() > 0) {
			TtIfMarketBean bean = new TtIfMarketBean();
			bean.setDealer_id(Long.parseLong(map.get("DEALER_ID").toString()));
			Map<String, Object> money = dao.getMarketFee(bean); 
			act.setOutData("money", money);
			//总金额=原来总金额+市场工单处理费用
			double amountSum = Double.parseDouble(String.valueOf(map.get("AMOUNT_SUM")));
			double sumMoney = Double.parseDouble(String.valueOf(money.get("SUM_MONEY") != null ? money.get("SUM_MONEY") : 0));
			double totalPrice = amountSum + sumMoney;
			map.put("AMOUNT_SUM", totalPrice);
		} 
	}
	
	/*
	 * 结算单明细 财务审核
	 */
	public void queryFinancialInfo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String id = request.getParamValue("id");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getBalanceMainMapView(id);//结算单主表信息
			List<Map<String, Object>> list = dao.getBalanceMainList(id);//结算单子表信息
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setForword(finInfoUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单财务室审核");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 结算单明细 财务室
	 */
	public void queryFinancialInfoView(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			//CommonUtils.checkNull() 校验是否为空
			String id = request.getParamValue("id");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getBalanceMainMapView(id);//结算单主表信息
			List<Map<String, Object>> list = dao.getBalanceMainList(id);//结算单子表信息
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setForword(finViewUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单明细");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 要求财务审核 
	 * 更改结算单状态
	 * 2010-11-04 修改
	 *      1、检测所有特殊费用是否都已经审核
	 *         新增：BalanceMainDao.queryAuthSpecAmount()方法
	 *               通过统计标识特殊费用工单数量和已审核特殊费用工单数量来判断
	 *               如果：标识数量为0 或 标识数据=已审核数据 那么 都已经审核
	 *               反之：存在未审核通过，不能转复合申请
	 *      2、需要根据特殊费用审核状态重新计算特殊费用
	 *         将审核通过的特殊费用和全部标识的特殊费用差累计到结算单的结算金额中
	 *      3、经审核通过的特殊费用工单修改为"已结算"
	 */
	public void financialModeAudit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		String SUCCESS = "SUCCESS";
		String id = "";
		String dealerId = "";
		try {
			RequestWrapper request = act.getRequest();
			id = request.getParamValue("id");
			String var = request.getParamValue("var");//版本号
			dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
			BalanceMainDao dao = new BalanceMainDao();
			//检测该结算单对应特殊费用是否都已经审核
//			Map<String,Object> specFeeMap = dao.queryAuthSpecAmount(Long.parseLong(id));
//			/** 标识特殊费用工单数 */
//			Integer specCount = Integer.parseInt(CommonUtils.getDataFromMap(specFeeMap, "ALLCOUNT").toString());
//			/** 已审核特殊费用工单数 */
//			Integer authCount = Integer.parseInt(CommonUtils.getDataFromMap(specFeeMap, "AUTH_COUNT").toString());
//			/** 标识特殊费用市场工单费用 */
//			Double marketFee = Double.parseDouble(CommonUtils.getDataFromMap(specFeeMap, "MARKETFEE").toString());
//			/** 标识特殊费用外出工单费用 */
//			Double outerFee = Double.parseDouble(CommonUtils.getDataFromMap(specFeeMap, "OUTFEE").toString());
//			/** 已审核特殊费用市场工单费用 */
//			Double authMarketFee = Double.parseDouble(CommonUtils.getDataFromMap(specFeeMap, "AUTH_MARKETFEE").toString());
//			/** 已审核特殊费用外出工单费用 */
//			Double authOuterFee = Double.parseDouble(CommonUtils.getDataFromMap(specFeeMap, "AUTH_OUTFEE").toString());
//			/** 特殊费用变化值 */
//			Double chanageFee = (authMarketFee+authOuterFee)-(marketFee+outerFee);
			//if(specCount<1 || specCount==authCount){
				boolean isDeal = DBLockUtil.lock(dealerId, DBLockUtil.BUSINESS_TYPE_08);
				if (isDeal) { //同步
					String newVar = dao.getNewVar(id, var);//获取版本号
					if(newVar.equals(var)){ 
						//结算单信息
						TtAsWrClaimBalancePO balancePO = dao.getClaimBalancePOById(Long.parseLong(id));
						Integer yieldly = -1;
						if(balancePO!=null && balancePO.getYieldly()!=null)
							yieldly = balancePO.getYieldly();
						//统计抵扣金额
						Map<String, Object> deductAmountMap = dao.getBalanceMainMap(id);
						
						String jiujianCount = CommonUtils.getDataFromMap(deductAmountMap, "TOTAL_AMOUNT").toString();//旧件扣款
						String kaoheCount = CommonUtils.getDataFromMap(deductAmountMap, "FINE_SUM").toString();//考核扣款
						String xingzhengCount = CommonUtils.getDataFromMap(deductAmountMap, "DAMOUNT").toString();//行政扣款
						jiujianCount = Utility.testString(jiujianCount)?jiujianCount:"0";
						kaoheCount = Utility.testString(kaoheCount)?kaoheCount:"0";
						xingzhengCount = Utility.testString(xingzhengCount)?xingzhengCount:"0";
						String zongjiCount = request.getParamValue("zongjiCount")==null?"0":request.getParamValue("zongjiCount");//结算金额
						String feiyongCount = request.getParamValue("feiyongCount")==null?"0":request.getParamValue("feiyongCount");//费用合计
						String returnAmount = request.getParamValue("RETURN_AMOUNT")==null?"0":request.getParamValue("RETURN_AMOUNT");//运费
						String repairAmount = request.getParamValue("repairAmount")==null?"0":request.getParamValue("repairAmount");//保养费扣款
						String activityAmount = request.getParamValue("activityAmount")==null?"0":request.getParamValue("activityAmount");//服务活动单扣款
						String remark = CommonUtils.checkNull(request.getParamValue("REMARK"));//备注
						String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode")); 
						TtAsWrClaimBalancePO po = new TtAsWrClaimBalancePO();
						TtAsWrClaimBalancePO tp = new TtAsWrClaimBalancePO();
						po.setId(Long.parseLong(id));
						tp.setReturnAmount(Double.parseDouble(returnAmount));
						tp.setOldDeduct(Double.parseDouble(jiujianCount));
						tp.setCheckDeduct(Double.parseDouble(kaoheCount));
						tp.setAdminDeduct(Double.parseDouble(xingzhengCount));
						tp.setFreeDeduct(Double.parseDouble(repairAmount));
						tp.setServiceDeduct(Double.parseDouble(activityAmount));
						//tp.setMarketAmount(authMarketFee);
						//tp.setSpeoutfeeAmount(authOuterFee);
						tp.setRemark(remark);
						tp.setVar(Integer.parseInt(var)+1);
						tp.setStatus(Integer.parseInt(Constant.ACC_STATUS_03));
						//tp.setAmountSum(Double.parseDouble(feiyongCount)+chanageFee);//加入特殊费用变动
						//tp.setBalanceAmount(Double.parseDouble(zongjiCount)+chanageFee);//加入特殊费用变动
						tp.setUpdateBy(logonUser.getUserId());
						Date updateDate = new Date();
						tp.setUpdateDate(updateDate);
						
						/********Ivesosn add by 2011-01-20****************/
						TcUserPO poUser =new TcUserPO();//根据userId找到用户名
						poUser.setUserId(logonUser.getUserId());
						TcUserPO poValue = (TcUserPO)dao.select(poUser).get(0);
						tp.setReviewApplicationBy(poValue.getName());//同时更新结算单复合申请人
						tp.setReviewApplicationTime(new Date());//同时更新结算单复合申请时间
						/********Ivesosn add by 2011-01-20****************/
						
						dao.update(po, tp);//更新TT_AS_WR_CLAIM_BALANCE
						
						
						/********add 20101201 zhumy**********/
						TtAsWrClaimBalancePO sel=(TtAsWrClaimBalancePO)dao.select(po).get(0);
						Date endDate=sel.getEndDate();
						TtAsDealerTypePO typeCon=new TtAsDealerTypePO();
						typeCon.setDealerId(sel.getDealerId());
						typeCon.setYieldly(sel.getYieldly().toString());
						TtAsDealerTypePO typeValue=new TtAsDealerTypePO();
						typeValue.setBalanceReviewDate(endDate);
						typeValue.setUpdateDate(new Date());
						typeValue.setUpdateBy(logonUser.getUserId().toString());
						dao.update(typeCon, typeValue);
						
						/********add 20101201 zhumy**********/
						
						//将处理过的"特殊费用"标识为"已支付"
						TtAsWrSpefeePO aa = new TtAsWrSpefeePO();
						aa.setYield(yieldly);
						aa.setDealerId(Long.parseLong(dealerId));
						aa.setClaimbalanceId(Long.parseLong(id));
						aa.setStatus(Integer.parseInt(Constant.SPEFEE_STATUS_06));//审核后的
						
						TtAsWrSpefeePO bb = new TtAsWrSpefeePO();
						bb.setStatus(Integer.parseInt(Constant.SPEFEE_STATUS_07));//锁定状态
						bb.setUpdateBy(logonUser.getUserId());
						bb.setUpdateDate(updateDate);
						dao.update(aa, bb);
						
						/*
						//将这个特殊费用的此次更改写入特殊费用审核明细表中
						TtAsWrSpefeePO pp = new TtAsWrSpefeePO();
						pp.setClaimbalanceId(Long.parseLong(id));
						List ppList = dao.select(pp);
						if(ppList.size()>0){
							for(int i=0;i<ppList.size();i++){
								pp = (TtAsWrSpefeePO)ppList.get(i) ;
								TtAsWrSpefeeAuditingPO auditPO = new TtAsWrSpefeeAuditingPO();
								auditPO.setAuditingDate(updateDate);
								auditPO.setAuditingPerson(logonUser.getName());
								auditPO.setCreateBy(logonUser.getUserId());
								auditPO.setCreateDate(updateDate);
								auditPO.setFeeId(pp.getId());
								auditPO.setId(Long.parseLong(SequenceManager.getSequence("")));
								auditPO.setStatus(Integer.parseInt(Constant.SPEFEE_STATUS_07));
								
								dao.insert(auditPO);
							}
						}*/
						
						//将处理过的抵扣单修改为"无效"
						TtAsWrDeductBalancePO tw = new TtAsWrDeductBalancePO();
						tw.setStatus(Constant.STATUS_ENABLE);
						tw.setDealerCode(dealerCode);
						tw.setYieldly(yieldly);
						
						TtAsWrDeductBalancePO td = new TtAsWrDeductBalancePO();
						td.setStatus(Constant.STATUS_DISABLE);
						td.setClaimbalanceId(Long.parseLong(id));
						td.setUpdateBy(tp.getUpdateBy());
						td.setUpdateDate(updateDate);
						
						dao.update(tw, td);//更新TT_AS_WR_DEDUCT_BALANCE
						
						//将处理过的奖惩记录修改为"无效"
						TtAsWrFinePO ta = new TtAsWrFinePO();
						TtAsWrFinePO tf = new TtAsWrFinePO();
						ta.setDealerId(Long.parseLong(dealerId));
						ta.setYieldly(yieldly);
						ta.setPayStatus(Integer.parseInt(Constant.PAY_STATUS_01));
						tf.setPayStatus(Integer.parseInt(Constant.PAY_STATUS_02));
						tf.setClaimbalanceId(Long.parseLong(id));
						tf.setUpdateBy(tp.getUpdateBy());
						tf.setUpdateDate(updateDate);
						dao.update(ta, tf);//更新TT_AS_WR_FINE
						
						/*
						 * add by zuoxj 2010-12-18  14：35
						 * 每次复核申请，都必将上次行政扣款转为已结算
						 */
						TtAsWrAdminDeductPO tc1 = new TtAsWrAdminDeductPO();
						TtAsWrAdminDeductPO ts1 = new TtAsWrAdminDeductPO();
						tc1.setDealerId(Long.parseLong(dealerId));
						tc1.setYieldly(yieldly);
						tc1.setDeductStatus(Integer.parseInt(Constant.ADMIN_STATUS_01));
						ts1.setDeductStatus(Integer.parseInt(Constant.ADMIN_STATUS_02));
						ts1.setClaimbalanceId(Long.parseLong(id));
						ts1.setUpdateBy(tp.getUpdateBy());
						ts1.setUpdateDate(updateDate);//更新TT_AS_WR_ADMIN_DEDUCT
						dao.update(tc1, ts1);
						
						/*if(Double.parseDouble(zongjiCount)<0){
							TtAsWrAdminDeductPO tc = new TtAsWrAdminDeductPO();
							tc.setId(Long.parseLong(SequenceManager.getSequence("")));
							tc.setDealerId(Long.parseLong(dealerId));
							TmDealerPO dpo = new TmDealerPO();
							dpo.setDealerId(Long.parseLong(dealerId));
							List dlist = dao.select(dpo);
							if(dlist.size()>0){
								dpo = (TmDealerPO)dlist.get(0);
								tc.setDealerCode(dpo.getDealerCode());
								tc.setDealerName(dpo.getDealerName());
							}
							tc.setYieldly(yieldly);
							 //将这次的 结算金额录为下次行政扣款金额
							tc.setDeductAmount(Double.parseDouble(zongjiCount)*(-1));
							tc.setDeductStatus(Integer.parseInt(Constant.ADMIN_STATUS_01));
							tc.setFromClaimbalanceId(Long.parseLong(id));
							tc.setOemCompanyId(Long.parseLong(logonUser.getOemCompanyId()));
							tc.setCreateBy(tp.getUpdateBy());
							tc.setCreateDate(updateDate);//更新TT_AS_WR_ADMIN_DEDUCT
							dao.insert(tc);
						}*/
						updateMarketStatus(Long.parseLong(dealerId));//更新TT_IF_MARKET
						
						/**********add by liuxh 20101127 复核申请完成更新 BALANCE_AMOUNT************/
						// BALANCE_AMOUNT减 保养费扣款 -服务活动单扣款-考核扣款-旧件扣款-行政抵扣-财务扣款
						StringBuffer sbSql=new StringBuffer();
//						sbSql.append("UPDATE TT_AS_WR_CLAIM_BALANCE SET BALANCE_AMOUNT=");
//						sbSql.append("(BALANCE_AMOUNT-(NVL(FREE_DEDUCT,0)+NVL(SERVICE_DEDUCT,0)+NVL(CHECK_DEDUCT,0)+NVL(OLD_DEDUCT,0)+NVL(ADMIN_DEDUCT,0)+NVL(FINANCIAL_DEDUCT,0))) ");
//						sbSql.append("WHERE ID=?");
						/*******mod by liuxh 201011201 复核申请结算金额重新计算再   -服务活动单扣款-考核扣款-旧件扣款-行政抵扣-财务扣款 ********/
						sbSql.append("UPDATE TT_AS_WR_CLAIM_BALANCE SET BALANCE_AMOUNT=((NVL(LABOUR_AMOUNT,0)+NVL(PART_AMOUNT,0)+NVL(OTHER_AMOUNT,0)+NVL(FREE_AMOUNT,0)");
						sbSql.append("+NVL(RETURN_AMOUNT,0)+NVL(MARKET_AMOUNT,0)+NVL(SPEOUTFEE_AMOUNT,0)+NVL(APPEND_AMOUNT,0)+NVL(SERVICE_TOTAL_AMOUNT,0))");
						sbSql.append("-(NVL(FREE_DEDUCT,0)+NVL(SERVICE_DEDUCT,0)+NVL(CHECK_DEDUCT,0)+NVL(OLD_DEDUCT,0)+NVL(ADMIN_DEDUCT,0)+NVL(FINANCIAL_DEDUCT,0)))\n");
						sbSql.append("WHERE ID=?");
						
						List parList=new ArrayList();
						parList.add(Long.parseLong(id));
						dao.update(sbSql.toString(), parList);
						
						/**********add by liuxh 20101127 复核申请完成更新 BALANCE_AMOUNT************/
						
						
						//记录日志表
						BalanceStatusRecord.recordStatus(Long.parseLong(id), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_06);
						act.setOutData("returnValue", "1");
							
					}else{
						act.setOutData("returnValue", 0);
					}
				}else{
					SUCCESS = "DEALED";
				}
//			}else{
//				SUCCESS = "NOTSATISFLED";
//			}
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,"财务复核申请");
			logger.error(logonUser,e1);
			act.setException(e1);
		}finally{
			DBLockUtil.freeLock(id, DBLockUtil.BUSINESS_TYPE_08);
			DBLockUtil.freeLock(dealerId, DBLockUtil.BUSINESS_TYPE_08);
		}
		act.setOutData("SUCCESS", SUCCESS);
	}
	
	/**
	 * 
	* @Title: updateMarketStatus 
	* @Description: TODO(点完复核申请,将状态更新成已结算) 
	* @param @param dealerId    经销商ID
	* @return void    返回类型 
	* @throws
	 */
	private void updateMarketStatus(Long dealerId) {
		TtIfMarketPO po = new TtIfMarketPO();
		po.setDealerId(dealerId);
		po.setStatus(Constant.MARKET_BACK_STATUS_TECH_PASS);
		TtIfMarketPO npo = new TtIfMarketPO();
		npo.setStatus(Constant.MARKET_BACK_STATUS_BALANCE);
		MarketQuesOrderDao dao = MarketQuesOrderDao.getInstance();
		dao.update(po, npo);
	}
	
	/*
	 * 生成开票通知单
	 */
	
	public void claimBalanceAudit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		String id = "";
		String SUCCESS = "SUCCESS";
		try {
			RequestWrapper request = act.getRequest();
			id = request.getParamValue("id");
			String var = request.getParamValue("var");//版本号
			BalanceMainDao dao = new BalanceMainDao();
			boolean isDeal = DBLockUtil.lock(id, DBLockUtil.BUSINESS_TYPE_09);
			if(isDeal) {//同步 
			String newVar = dao.getNewVar(id, var);//获取版本号
				if(newVar.equals(var)){
					String financialDeduct = request.getParamValue("financialDeduct")==null?"0":request.getParamValue("financialDeduct");//财务抵扣
					String noteCount = request.getParamValue("noteCount")==null?"0":request.getParamValue("noteCount");//开票总金额
					String financialRemark = CommonUtils.checkNull(request.getParamValue("financialRemark"));
					TtAsWrClaimBalancePO po = new TtAsWrClaimBalancePO();
					TtAsWrClaimBalancePO tp = new TtAsWrClaimBalancePO();
					po.setId(Long.parseLong(id));
					tp.setFinancialDeduct(Double.parseDouble(financialDeduct));
					tp.setNoteAmount(Double.parseDouble(noteCount));
					tp.setFunancialRemark(financialRemark);
					tp.setVar(Integer.parseInt(var)+1);
					tp.setStatus(Integer.parseInt(Constant.ACC_STATUS_04));
					tp.setUpdateBy(logonUser.getUserId());
					Date updateDate = new Date();
					tp.setUpdateDate(updateDate);
					dao.update(po, tp);//更新TT_AS_WR_CLAIM_BALANCE	
					
					//记录日志表
					BalanceStatusRecord.recordStatus(Long.parseLong(id), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_07);
					act.setOutData("returnValue", "1");
				}else{
					act.setOutData("returnValue", 0);
				}
			}else{
				SUCCESS = "DEALED";
			}
		}catch(Exception e) {//异常方法
			SUCCESS = "FAILURE";
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,"生成开票通知单");
			logger.error(logonUser,e1);
			act.setException(e1);
		}finally{
			DBLockUtil.freeLock(id, DBLockUtil.BUSINESS_TYPE_09);
		}
		act.setOutData("SUCCESS", SUCCESS);
	}
	
	/*
	 * 转行政扣款
	 */
	public void deductBalanceAudit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		String id = "";
		String SUCCESS = "SUCCESS";
		try {
			RequestWrapper request = act.getRequest();
			id = request.getParamValue("id");
			String var = request.getParamValue("var");//版本号
			BalanceMainDao dao = new BalanceMainDao();
			boolean isDeal = DBLockUtil.lock(id, DBLockUtil.BUSINESS_TYPE_10);
			if (isDeal){ 
			String newVar = dao.getNewVar(id, var);//获取版本号
				if(newVar.equals(var)){
					String financialDeduct = request.getParamValue("financialDeduct")==null?"0":request.getParamValue("financialDeduct");//财务抵扣
					String noteCount = request.getParamValue("noteCount")==null?"0":request.getParamValue("noteCount");//开票总金额
					String deductAmount = request.getParamValue("deductAmount")==null?"0":request.getParamValue("deductAmount");//开票总金额
					String financialRemark = CommonUtils.checkNull(request.getParamValue("financialRemark"));
					String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
					String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode"));
					String dealerName = CommonUtils.checkNull(request.getParamValue("dealerName"));  
					TtAsWrClaimBalancePO po = new TtAsWrClaimBalancePO();
					TtAsWrClaimBalancePO tp = new TtAsWrClaimBalancePO();
					po.setId(Long.parseLong(id));
					tp.setFinancialDeduct(Double.parseDouble(financialDeduct));
					tp.setNoteAmount(Double.parseDouble(noteCount));
					tp.setFunancialRemark(financialRemark);
					tp.setVar(Integer.parseInt(var)+1);
					tp.setStatus(Integer.parseInt(Constant.ACC_STATUS_04));
					tp.setUpdateBy(logonUser.getUserId());
					Date updateDate = new Date();
					tp.setUpdateDate(updateDate);
					dao.update(po, tp);//更新TT_AS_WR_CLAIM_BALANCE	
					
					//结算单信息
					TtAsWrClaimBalancePO balancePO = dao.getClaimBalancePOById(Long.parseLong(id));
					Integer yieldly = -1;
					if(balancePO!=null && balancePO.getYieldly()!=null)
						yieldly = balancePO.getYieldly();
					
					Double zjCount = Math.abs(Utility.getDouble(deductAmount));
					
					TtAsWrAdminDeductPO dp = new TtAsWrAdminDeductPO();
					dp.setId(Long.parseLong(SequenceManager.getSequence("")));
					dp.setDealerId(Long.parseLong(dealerId));
					dp.setDealerCode(dealerCode);
					dp.setDealerName(dealerName);
					dp.setDeductAmount(zjCount);
					dp.setDeductStatus(Integer.parseInt(Constant.ADMIN_STATUS_01));
					dp.setFromClaimbalanceId(Long.parseLong(id));
					dp.setCreateBy(tp.getUpdateBy());
					dp.setCreateDate(tp.getUpdateDate());
					dp.setOemCompanyId(GetOemcompanyId.getOemCompanyId(logonUser));
					dp.setYieldly(yieldly);
					dao.insert(dp);//新增TT_AS_WR_ADMIN_DEDUCT
					
					//记录日志表
					BalanceStatusRecord.recordStatus(Long.parseLong(id), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_07);
					
					act.setOutData("returnValue", "1");
					
				}else{
					act.setOutData("returnValue", 0);
				}
			}else{
				SUCCESS = "DEALED";
			}
		}catch(Exception e) {//异常方法
			SUCCESS = "ERROR";
			act.setOutData("returnValue", "ERROR");
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,"转行政扣款单");
			logger.error(logonUser,e1);
			act.setException(e1);
		}finally{
			DBLockUtil.freeLock(id, DBLockUtil.BUSINESS_TYPE_10);
		}
		act.setOutData("SUCCESS", SUCCESS);
	}
	
	/*
	 * 经销商查看开票结果
	 */
	public void dealerBalanceQueryInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(delaerUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单管理");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 查看开票结果明细
	 */
	public void queryDealerBalanceInfo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String id = request.getParamValue("id");
			String infoFlag = request.getParamValue("infoFlag");
			BalanceMainDao dao = new BalanceMainDao();
			Map<String, Object> map = dao.getDealerQueryInfo(id);
			List<Map<String, Object>> detail =  dao.getBalanceMainList1(id);
			//List<Map<String, Object>> unit =  dao.getinvoiceUnit(id);
			act.setOutData("infoFlag", infoFlag);
			act.setOutData("map", map);
			act.setOutData("detail", detail);
			//act.setOutData("unit", unit);
			act.setForword(delaerInfoUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"结算单管理");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 经销商确认
	 */
	public void checkBalanceFor(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			String id = request.getParamValue("id");
			TtAsWrClaimBalancePO po = new TtAsWrClaimBalancePO();
			TtAsWrClaimBalancePO tp = new TtAsWrClaimBalancePO();
			po.setId(Long.parseLong(id));
			tp.setStatus(Integer.parseInt(Constant.ACC_STATUS_05));
			tp.setUpdateBy(logonUser.getUserId());
			tp.setUpdateDate(new Date());
			BalanceMainDao dao = new BalanceMainDao();
			dao.update(po, tp);
			
			//记录日志表 -- 添加一个经销商确认时间
			BalanceStatusRecord.recordStatus(Long.parseLong(id), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_08);
			act.setForword(delaerUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"经销商确认");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void oemBalanceQueryInit() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
		   //取得该用户拥有的产地权限
	       String yieldly = CommonUtils.findYieldlyByPoseId(logonUser.getPoseId());
	      
	        act.setOutData("yieldly", yieldly);
			act.setForword(oemUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"经销商开票确认查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**********
	 * :开票通知单打印
	 * 
	 */
	public void invoicePrint(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			BalanceMainDao dao = new BalanceMainDao();
			String id =request.getParamValue("id");
			List<Map<String, Object>> detail = dao.getBalanceMainList(id);
			List<Map<String, Object>> list = dao.getinvoiceView(id);
			List l = dao.getDate2(id) ;
			if(l.size()>0){
				act.setOutData("audit", (TtAsWrBalanceAuthitemPO)l.get(0));
			}
			act.setOutData("list", list.get(0));
			act.setOutData("detail", detail);
			act.setForword(invoicePrint);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"经销商确认");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	//根据结算单ID判断复核申请的条件
	public void dealerTimeJuge(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			BalanceMainDao dao = new BalanceMainDao();
			RequestWrapper request = act.getRequest();
			String balanceId = request.getParamValue("id");//结算单ID
			String msg=dao.dealerTimeJuge(Long.valueOf(balanceId));
			act.setOutData("msg", msg);
		}catch(Exception e){
			e.printStackTrace();
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"ERROR");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 收单汇总的一个打印
	 */
	public void getClaimInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(CLAIM_INIT_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	public void claimPrintQuery(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper req = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String bDate = req.getParamValue("bDate");
			String eDate = req.getParamValue("eDate");
			String name = req.getParamValue("name");
			BalanceMainDao dao = new BalanceMainDao();
			Integer curPage = req.getParamValue("curPage") != null ? Integer
					.parseInt(req.getParamValue("curPage"))
					: 1; // 处理当前页
			int pageSize = 15 ;
			PageResult<Map<String,Object>> ps = dao.getClaimPrint(bDate, eDate, name,logonUser.getCompanyId() ,pageSize, curPage,logonUser.getPoseId());
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	public void goPrint(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper req = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String bDate = req.getParamValue("bDate");
			String eDate = req.getParamValue("eDate");
			String name = req.getParamValue("name");
			BalanceMainDao dao = new BalanceMainDao();
			
			PageResult<Map<String,Object>> ps = dao.getClaimPrint(bDate, eDate, name,logonUser.getCompanyId() ,10000, 1,logonUser.getPoseId());
			act.setOutData("list", ps.getRecords());
			act.setOutData("bDate", bDate);
			act.setOutData("eDate", eDate);
			act.setForword(CLAIM_PRINT_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * Iverson add By 2010-12-16
	 * 打印收票报表
	 */
	public void getPrintPorterInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(PRINTPROTER_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * Iverson add By 2010-12-16
	 * 打印收票报表(查询分页)
	 */
	public void printPorterQuery(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper req = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String bDate = req.getParamValue("bDate");
			String eDate = req.getParamValue("eDate");
			String name = req.getParamValue("name");
			String report_code = req.getParamValue("report_code");
			String financeName = req.getParamValue("financeName");
			String gzDate = req.getParamValue("gzDate");
			String gzDate1 = req.getParamValue("gzDate1");
			BalanceMainDao dao = new BalanceMainDao();
			Integer curPage = req.getParamValue("curPage") != null ? Integer
					.parseInt(req.getParamValue("curPage"))
					: 1; // 处理当前页
			int pageSize = 15 ;
			PageResult<Map<String,Object>> ps = dao.printPorterQuery(bDate, eDate, name,report_code,financeName,gzDate,gzDate1,logonUser.getCompanyId() ,pageSize, curPage,logonUser.getPoseId());
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void exportExcel(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper req = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String bDate = req.getParamValue("bDate");
			String eDate = req.getParamValue("eDate");
			String name = req.getParamValue("name");
			String report_code = req.getParamValue("report_code");
			String financeName = req.getParamValue("financeName");
			String gzDate = req.getParamValue("gzDate");
			String gzDate1 = req.getParamValue("gzDate1");
			BalanceMainDao dao = new BalanceMainDao();
			Integer curPage = req.getParamValue("curPage") != null ? Integer
					.parseInt(req.getParamValue("curPage"))
					: 1; // 处理当前页
			int pageSize = 15 ;
			List<Map<String,Object>> list = dao.exportExcel(bDate, eDate, name,report_code,financeName,gzDate,gzDate1,logonUser.getCompanyId() ,pageSize, curPage,logonUser.getPoseId());
			String[] head=new String[11];
			head[0]="汇总单号";
			head[1]="经销商代码";
			head[2]="经销商名称";
			head[3]="省份";
			head[4]="发票号码";
			head[5]="发票金额";
			head[6]="税率";
			head[7]="收票时间";
			head[8]="挂账时间";
			head[9]="财务人员";
			head[10]="签收人";
			

			
		    List list1=new ArrayList();
		    if(list!=null&&list.size()!=0){
				for(int i=0;i<list.size();i++){
			    	Map map =(Map)list.get(i);
			    	if(map!=null&&map.size()!=0){
						String[]detail=new String[11];
						detail[0] = String.valueOf(map.get("REPORT_CODE"));
						detail[1] = String.valueOf(map.get("DEALER_CODE"));
						detail[2] = String.valueOf(map.get("DEALER_NAME"));
						detail[3] = String.valueOf(map.get("REGION_NAME"));
						detail[4] = String.valueOf(map.get("INVOICE_CODE"));
						detail[5] = String.valueOf(map.get("AMOUNT"));
						detail[6] = String.valueOf(map.get("TAX_RATE"));
						detail[7] = String.valueOf(map.get("AUTH_TIME"));
						detail[8] = String.valueOf(map.get("GZTIME"));
						detail[9] = String.valueOf(map.get("AUTH_PERSON_NAME"));
						detail[10] = String.valueOf(map.get("A_NAME"));
						
						list1.add(detail);
			    	}
			      }
				com.infodms.dms.actions.claim.basicData.ToExcel.toNewExcel(ActionContext.getContext().getResponse(), req, head, list1,"导出收票报表.xls");
		    }
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * Iverson add By 2010-12-16
	 * 打印收票报表(打印)
	 */
	public void printPorter(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper req = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String bDate = req.getParamValue("bDate");
			String eDate = req.getParamValue("eDate");
			String name = req.getParamValue("name");
			String report_code = req.getParamValue("report_code");
			String financeName = req.getParamValue("financeName");
			String gzDate = req.getParamValue("gzDate");
			String gzDate1 = req.getParamValue("gzDate1");
			BalanceMainDao dao = new BalanceMainDao();
			
			PageResult<Map<String,Object>> ps = dao.printPorterQuery(bDate, eDate, name,report_code,financeName,gzDate,gzDate1,logonUser.getCompanyId() ,10000, 1,logonUser.getPoseId());
			act.setOutData("list", ps.getRecords());
			act.setOutData("bDate", bDate);
			act.setOutData("eDate", eDate);
			act.setOutData("name", name);
			act.setForword(PORTER_PRINT_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"汇总打印页面查询失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/*******
	 * add by liuxh 20110110 增加复核申请时退回功能
	 */
	public void backToAudit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			BalanceMainDao dao = new BalanceMainDao();
			RequestWrapper request = act.getRequest();
			String balanceId = request.getParamValue("id");//结算单ID
			StringBuffer sbSql=new StringBuffer();
			sbSql.append("UPDATE TT_AS_WR_CLAIM_BALANCE K SET K.STATUS=?,K.UPDATE_BY=?,K.UPDATE_DATE=SYSDATE WHERE K.ID=? " );
			List listPar=new ArrayList();
			listPar.add(Constant.ACC_STATUS_01);
			listPar.add(logonUser.getUserId());
			listPar.add(balanceId);
			dao.update(sbSql.toString(), listPar);
			String sql="DELETE FROM TT_AS_WR_BALANCE_AUTHITEM WHERE AUTH_STATUS=? AND BALANCE_ID=? ";
			List listDel=new ArrayList();
			listDel.add(BalanceStatusRecord.STATUS_04);
			listDel.add(balanceId);
			dao.update(sql, listDel);
			BalanceStatusRecord.recordStatus(Long.parseLong(balanceId), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_15);
			act.setOutData("msg", "true");
		}catch(Exception e){
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"复核申请退回失败");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * add by zuoxj 2011-01-26
	 * 结算单，财务在复核时的回退功能
	 *   步骤：
	 *      0、首先判断此结算单能不能回退
	 *         -- 如果此结算单的结束日期与结算审核后日期相同，则允许回退，反正拒绝
	 *      1、将特殊费用状态改为-- 已结算
	 *      2、旧件抵扣与此结算单的关系断掉，并更改状态为-- 有效 10011001
	 *      3、奖惩与此结单的关系断掉，并更改状态为-- 未支付11511001
	 *      4、行政扣款与此结算单的关系断掉，将更改状态为-- 未支付11521001
	 *      5、清除审核此结算单的相应记录，11841006
	 *      6、清空此结算单的旧件扣款，考核扣款，行政扣款
	 *      7、重新计算结算费用
	 */
	public void financialBack(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			BalanceMainDao dao = new BalanceMainDao();
			RequestWrapper req = act.getRequest() ;
			String balanceNo = req.getParamValue("balanceNo");
			
			//0、首先判断此结算单能不能回退
			//   -- 如果此结算单的结束日期与结算审核后日期相同，则允许回退，反正拒绝
			StringBuffer checkSql = new StringBuffer("\n") ;
			checkSql.append("select count(1) amount\n");
			checkSql.append("  from tt_as_wr_claim_balance b, tt_as_dealer_type d\n");  
			checkSql.append(" where b.dealer_id = d.dealer_id\n");  
			checkSql.append("   and b.end_date = d.balance_review_date\n");  
			checkSql.append("   and b.balance_no = '").append(balanceNo).append("'\n");
			Map<String,Object> map = dao.checkNum(checkSql.toString()) ;
	
				//将结算审核时期更改为此结算单起始日期的前一天
				StringBuffer viewdateSql = new StringBuffer("\n") ;
				viewdateSql.append("update tt_as_dealer_type t\n");
				viewdateSql.append("   set t.balance_review_date = (select b.start_date - 1\n");  
				viewdateSql.append("                                  from tt_as_wr_claim_balance b\n");  
				viewdateSql.append("                                 where b.balance_no = '").append(balanceNo).append("')\n");  
				viewdateSql.append(" where t.dealer_id =\n");  
				viewdateSql.append("       (select b.dealer_id\n");  
				viewdateSql.append("          from tt_as_wr_claim_balance b\n");  
				viewdateSql.append("         where b.balance_no = '").append(balanceNo).append("')\n");  
				viewdateSql.append("   and t.yieldly = (select b.yieldly\n");  
				viewdateSql.append("                      from tt_as_wr_claim_balance b\n");  
				viewdateSql.append("                     where b.balance_no = '").append(balanceNo).append("')\n");
				dao.update(viewdateSql.toString(),null) ;
			
				//1、将特殊费用状态改为-- 已结算
				StringBuffer spefeeSql = new StringBuffer("\n") ;
				spefeeSql.append("update tt_as_wr_spefee s\n");
				spefeeSql.append("   set s.status = ").append(Constant.SPEFEE_STATUS_06).append(",\n");
				spefeeSql.append("       s.update_date = sysdate,\n");
				spefeeSql.append("       s.update_by = ").append(logonUser.getUserId()).append("\n");  
				spefeeSql.append(" where s.status = ").append(Constant.SPEFEE_STATUS_07).append("\n");  
				spefeeSql.append("   and s.claimbalance_id = \n");  
				spefeeSql.append("       (select id from tt_as_wr_claim_balance b where b.balance_no = '").append(balanceNo).append("')\n");
				dao.update(spefeeSql.toString(), null) ;
				
				//2、旧件抵扣与此结算单的关系断掉，并更改状态为-- 有效 10011001
				StringBuffer oldpartSql = new StringBuffer("\n") ;
				oldpartSql.append("update tt_as_wr_deduct_balance d\n");
				oldpartSql.append("   set d.status = ").append(Constant.STATUS_ENABLE).append(",\n");
				oldpartSql.append("       d.claimbalance_id = '',\n");
				oldpartSql.append("       d.update_date = sysdate,\n");  
				oldpartSql.append("       d.update_by = ").append(logonUser.getUserId()).append("\n");
				oldpartSql.append(" where d.status = ").append(Constant.STATUS_DISABLE).append("\n");  
				oldpartSql.append("   and d.claimbalance_id =\n");  
				oldpartSql.append("       (select id from tt_as_wr_claim_balance b where b.balance_no = '").append(balanceNo).append("')\n");
				dao.update(oldpartSql.toString(),null) ;
				
				//3、奖惩与此结单的关系断掉，并更改状态为-- 未支付11511001
				StringBuffer fineSql = new StringBuffer("\n") ;
				fineSql.append("update tt_as_wr_fine f\n");
				fineSql.append("   set f.claimbalance_id = '',\n");  
				fineSql.append("       f.pay_status = ").append(Constant.PAY_STATUS_01).append(",\n");  
				fineSql.append("       f.update_by = ").append(logonUser.getUserId()).append(",\n");  
				fineSql.append("       f.update_date = sysdate\n");  
				fineSql.append(" where f.pay_status = ").append(Constant.PAY_STATUS_02).append("\n");  
				fineSql.append("   and f.claimbalance_id =\n");  
				fineSql.append("       (select id from tt_as_wr_claim_balance b where b.balance_no = '").append(balanceNo).append("')\n");
				dao.update(fineSql.toString(),null) ;
				
				//4、行政扣款与此结算单的关系断掉，将更改状态为-- 未支付11521001
				StringBuffer adminSql = new StringBuffer("\n");
				adminSql.append("update tt_as_wr_admin_deduct d\n");
				adminSql.append("   set d.claimbalance_id = '',\n");  
				adminSql.append("       d.deduct_status = ").append(Constant.ADMIN_STATUS_01).append(",\n");  
				adminSql.append("       d.update_by = ").append(logonUser.getUserId()).append(",\n");  
				adminSql.append("       d.update_date = sysdate\n");  
				adminSql.append(" where d.deduct_status = ").append(Constant.ADMIN_STATUS_02).append("\n");  
				adminSql.append("   and d.claimbalance_id =\n");  
				adminSql.append("       (select id from tt_as_wr_claim_balance b where b.balance_no = '").append(balanceNo).append("')\n");
	            dao.update(adminSql.toString(), null);
	            
				//5、清除审核此结算单的相应记录，11861006
				StringBuffer authSql = new StringBuffer("\n");
				authSql.append("delete from tt_as_wr_balance_authitem a\n");
				authSql.append(" where a.auth_status = ").append(BalanceStatusRecord.STATUS_06).append("\n");  
				authSql.append("   and a.balance_id =\n");  
				authSql.append("       (select id from tt_as_wr_claim_balance b where b.balance_no = '").append(balanceNo).append("')\n");
				dao.delete(authSql.toString(),null) ;
				
				//6、清空此结算单的旧件扣款，考核扣款，行政扣款
				StringBuffer balanceSql = new StringBuffer("\n");
				balanceSql.append("update tt_as_wr_claim_balance b\n");
				balanceSql.append("   set b.check_deduct = 0,\n");  
				balanceSql.append("       b.old_deduct = 0,\n");  
				balanceSql.append("       b.admin_deduct = 0,\n");
				balanceSql.append("       b.FREE_DEDUCT = 0,\n");
				balanceSql.append("       b.SERVICE_DEDUCT = 0,\n");
				balanceSql.append("       b.return_amount = b.return_amount_bak,\n");
	            balanceSql.append("       b.status = ").append(Constant.ACC_STATUS_02).append(",\n"); 
				balanceSql.append("       b.update_by = ").append(logonUser.getUserId()).append(",\n");  
				balanceSql.append("       b.update_date = sysdate\n");  
				balanceSql.append(" where b.balance_no = '").append(balanceNo).append("'\n");
				dao.update(balanceSql.toString(),null) ;
				
				//7、重新计算结算费用 -- 引用复核申请统计金额的SQL
				StringBuffer sbSql=new StringBuffer();
				sbSql.append("UPDATE TT_AS_WR_CLAIM_BALANCE SET BALANCE_AMOUNT=((NVL(LABOUR_AMOUNT,0)+NVL(PART_AMOUNT,0)+NVL(OTHER_AMOUNT,0)+NVL(FREE_AMOUNT,0)");
				sbSql.append("+NVL(RETURN_AMOUNT,0)+NVL(MARKET_AMOUNT,0)+NVL(SPEOUTFEE_AMOUNT,0)+NVL(APPEND_AMOUNT,0)+NVL(SERVICE_TOTAL_AMOUNT,0))");
				sbSql.append("-(NVL(FREE_DEDUCT,0)+NVL(SERVICE_DEDUCT,0)+NVL(CHECK_DEDUCT,0)+NVL(OLD_DEDUCT,0)+NVL(ADMIN_DEDUCT,0)+NVL(FINANCIAL_DEDUCT,0)))\n");
				sbSql.append("WHERE balance_no = '").append(balanceNo).append("'\n");
				dao.update(sbSql.toString(), null);
				
				//记录日志表 -- 添加一个经销商确认时间
				TtAsWrClaimBalancePO po = new TtAsWrClaimBalancePO();
				po.setBalanceNo(balanceNo);
				BalanceStatusRecord.recordStatus(((TtAsWrClaimBalancePO)dao.select(po).get(0)).getId(), logonUser.getUserId(), logonUser.getName(), logonUser.getOrgId(), BalanceStatusRecord.STATUS_BACK);
				
				act.setOutData("flag", true);
			
		}catch(Exception e){
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"财务复核退回失败");
			logger.error(logonUser,e1);
			act.setOutData("flag", false);
			act.setException(e1);
		}
	}
}

































